package com.zzr.demo.redis.service.impl;

import com.zzr.demo.redis.service.QueueService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author: xiaomi
 * @date: 2021/10/8
 * @description: 使用 list 完成 FIFO 的队列
 * left 作为头；right 作为尾
 */
@Service
@Slf4j
public class FIFOQueueServiceImpl implements QueueService {

    final String QUEUE_KEY = "test::fifo::queue";
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean enqueue(String item) {
        ListOperations<String, String> opsForList = stringRedisTemplate.opsForList();
        //LPUSH
        Long num = opsForList.leftPush(QUEUE_KEY, item);
        //入队后元素数量大于0
        return num > 0;
    }

    @Override
    public String dequeue() {
        ListOperations<String, String> opsForList = stringRedisTemplate.opsForList();
        String item = opsForList.rightPop(QUEUE_KEY);
        log.info("dequeue:{}", item);
        return item;
    }
}
